<template>
  <div class="cancellation-container">
    <el-card shadow="hover" class="!border-0">
      <template #header>
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-xl font-semibold text-gray-800">取消预订申请</h2>
            <p class="text-gray-500 text-sm">审核客户的取消预订申请并处理退款</p>
          </div>
          <el-button
            @click="fetchRequests"
            :loading="loading"
            type="primary"
            class="refresh-button !w-auto"
          >
            <RefreshCw class="h-4 w-4" />
            刷新
          </el-button>
        </div>
      </template>

      <div v-if="pendingCancellations.length > 0" class="cancellation-grid">
        <el-card
          v-for="request in pendingCancellations"
          :key="request.bookingId"
          shadow="hover"
          class="cancellation-card"
        >
          <div class="p-4">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
              <div class="space-y-2">
                <div class="space-y-2">
                  <h4 class="font-semibold text-gray-800">{{ request.fullName || '未知客户' }}</h4>
                  <p class="text-sm text-gray-600">
                    <strong>订单号：</strong>
                    {{ request.bookingId }}
                  </p>
                  <p class="text-sm text-gray-600">
                    <strong>账户名：</strong>
                    {{ request.username }}
                  </p>
                  <p class="text-sm text-gray-600">
                    <strong>会议室：</strong>
                    {{ request.roomName }}
                  </p>
                </div>
                <p class="text-sm text-gray-600">
                  <strong>原定时间：</strong>
                  {{ new Date(request.startTime).toLocaleString() }}
                </p>
                <p class="text-sm text-gray-600">
                  <strong>申请时间：</strong>
                  {{ new Date(request.cancellationRequestedAt).toLocaleString() }}
                </p>
              </div>

              <div class="space-y-2">
                <p class="text-sm text-gray-600">
                  <strong>取消原因：</strong>
                  {{ request.reason || '无' }}
                </p>
                <el-alert
                  :title="`退款金额：¥${calculateRefundAmount(request)}`"
                  :description="`退款比例：${getRefundRate(request)}`"
                  type="success"
                  :closable="false"
                  show-icon
                  class="!py-2"
                />
              </div>

              <div class="flex flex-col gap-2 button-container">
                <el-button
                  @click="approveCancellation(request)"
                  type="success"
                  class="action-button"
                >
                  <CheckCircleIcon class="h-4 w-4 mr-2" />
                  批准并退款
                </el-button>
                <el-button @click="rejectCancellation(request)" type="danger" class="action-button">
                  <XCircleIcon class="h-4 w-4 mr-2" />
                  拒绝申请
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-state">
        <el-empty description="没有待审核的取消预订申请" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox, ElCard, ElButton, ElAlert, ElEmpty } from 'element-plus'

// Import Lucide-Vue-Next icons
import { CheckCircle as CheckCircleIcon, XCircle as XCircleIcon, RefreshCw } from 'lucide-vue-next'

const pendingCancellations = ref([])
const loading = ref(false)

const fetchRequests = async () => {
  const authStore = useAuthStore()
  await authStore.checkAuth() // 确保用户信息已加载

  try {
    loading.value = true
    const response = await axios.get('http://localhost:8080/api/reservations/cancellation-requests')
    console.log('Fetched reservations:', response.data)
    pendingCancellations.value = response.data.filter(
      (reservation) => reservation.status === 'CANCELLATION_REQUESTED'
    )
    ElMessage.success('数据已更新')
  } catch (error) {
    console.error('Error fetching reservations:', error)
    ElMessage.error(error.response?.data?.message || '获取预订信息时发生错误。')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchRequests()
})

defineExpose({
  fetchRequests,
})

const approveCancellation = async (request) => {
  try {
    await ElMessageBox.confirm(
      `确定要批准${request.fullName || '该客户'}的取消申请并退款¥${calculateRefundAmount(
        request
      )}吗？`,
      '确认批准',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    console.log('Request object:', request)
    const authStore = useAuthStore()
    const employeeId = authStore.user?.userId

    if (!employeeId) {
      ElMessage.error('员工未认证。请登录。')
      return
    }

    const response = await axios.put(
      `http://localhost:8080/api/reservations/cancel-approve/${request.bookingId}/${employeeId}`
    )

    if (response.data) {
      ElMessage.success('取消请求已成功批准！')
      pendingCancellations.value = pendingCancellations.value.filter(
        (req) => req.bookingId !== request.bookingId
      )
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error approving cancellation:', error)
      ElMessage.error(error.response?.data?.message || '批准取消请求时发生错误。')
    }
  }
}

const rejectCancellation = async (request) => {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝${request.fullName || '该客户'}的取消申请吗？`,
      '确认拒绝',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const authStore = useAuthStore()
    const employeeId = authStore.user?.userId

    if (!employeeId) {
      ElMessage.error('员工未认证。请登录。')
      return
    }

    const response = await axios.put(
      `http://localhost:8080/api/reservations/cancel-reject/${request.bookingId}/${employeeId}`
    )

    if (response.data) {
      ElMessage.success('取消请求已成功拒绝！')
      pendingCancellations.value = pendingCancellations.value.filter(
        (req) => req.bookingId !== request.bookingId
      )
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error rejecting cancellation:', error)
      ElMessage.error(error.response?.data?.message || '拒绝取消请求时发生错误。')
    }
  }
}

const calculateRefundAmount = (request) => {
  const startTime = new Date(request.startTime)
  const cancellationTime = new Date(request.cancellationRequestedAt)
  const timeDifferenceHours = (startTime.getTime() - cancellationTime.getTime()) / (1000 * 60 * 60)

  let refundRate = 0
  if (timeDifferenceHours >= 72) {
    refundRate = 1
  } else if (timeDifferenceHours >= 48) {
    refundRate = 0.75
  } else if (timeDifferenceHours >= 24) {
    refundRate = 0.25
  } else {
    refundRate = 0
  }

  return (request.totalPrice * refundRate).toFixed(2)
}

const getRefundRate = (request) => {
  const startTime = new Date(request.startTime)
  const cancellationTime = new Date(request.cancellationRequestedAt)
  const timeDifferenceHours = (startTime.getTime() - cancellationTime.getTime()) / (1000 * 60 * 60)

  if (timeDifferenceHours >= 72) {
    return '100%'
  } else if (timeDifferenceHours >= 48) {
    return '75%'
  } else if (timeDifferenceHours >= 24) {
    return '25%'
  } else {
    return '0%'
  }
}
</script>

<style scoped>
.cancellation-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.cancellation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
}

.cancellation-card {
  height: 100%;
  transition: all 0.3s ease;
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.cancellation-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.empty-state {
  padding: 2rem;
  text-align: center;
}

/* Element Plus 样式覆盖 */
:deep(.el-card) {
  border: none !important;
  overflow: hidden;
}

:deep(.el-card__header) {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-card__body) {
  padding: 1.5rem;
}

/* 响应式布局 */
@media (max-width: 1280px) {
  .cancellation-grid {
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  }
}

@media (max-width: 768px) {
  .cancellation-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

/* 申请卡片内容样式 */
.request-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.info-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.info-label {
  font-weight: 600;
  color: #374151;
  font-size: 0.875rem;
}

.info-value {
  color: #6b7280;
  font-size: 0.875rem;
}

/* 按钮组样式 */
.action-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.button-container {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 100%;
}

.action-button {
  width: 100% !important;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 刷新按钮样式重写 */
.refresh-button {
  min-width: 80px !important;
  padding: 8px 16px !important;
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

:deep(.refresh-button .lucide) {
  width: 16px;
  height: 16px;
}

/* 提示信息样式 */
:deep(.el-alert) {
  margin: 1rem 0;
  border-radius: 0.5rem;
}

.refund-info {
  background-color: #f0f9ff;
  border-radius: 0.5rem;
  padding: 1rem;
  margin: 1rem 0;
}

/* 移除之前的通用按钮宽度设置 */
:deep(.el-button) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

/* 确保图标和文字对齐 */
:deep(.el-button .lucide) {
  margin: 0;
  vertical-align: middle;
}
</style>
